<template>
  <div id="questionAppPage">
    <h2 style="margin-bottom: 32px">创建题目</h2>
    <a-form
            :model="form"
            :style="{ width: '480px' }"
            label-align="left"
            auto-label-width
            @submit="handleSubmit"
    >
      <a-form-item label="应用 id">
        {{appId}}
      </a-form-item>
      <a-form-item label="题目列表" :content-flex="false" :merge-props="false">
        <a-space size="large">
          <a-button @click="addQuestion(questionContent.length)">
            底部添加标题
          </a-button>
          <!--抽屉，【向子组件传递appId，接收子组件的onSuccess方法】-->
          <AiGenerateDrawer
                  :appId="appId"
                  :onSuccess="onAiGenerateQuestion"
                  :onSEESuccess="onAiGenerateQuestionSSE"
                  :onSSEStart="onSSEStartGenerate"
                  :onSSEClose="onSSEStartClose"
          >

          </AiGenerateDrawer>
        </a-space>

        <!--展示底部添加标题这个按钮的效果,即遍历每道题目-->
        <div v-for="(question,index) in questionContent" :key="index" style="margin-top: 24px">
          <a-space size="large">
            <h3>题目{{index + 1}}</h3>
            <a-button size="samll" @click="addQuestion(index + 1)">添加题目</a-button>
            <a-button size="small" status="danger" @click="deleteQuestion(index)">删除题目</a-button>
          </a-space>
          <a-form-item field="posts.post1" :label="`题目${index + 1}标题`">
            <a-input v-model="question.title" placeholder="请输入标题" />
          </a-form-item>
          <!---->

          <!--展示选项下拉框-->
          <a-space size="large">
            <h4>题目{{index + 1}}选项列表</h4>
            <a-button @click="addQuestionOptions(question,questionContent.length)">
              添加选项
            </a-button>
          </a-space>
          <a-form-item
                  v-for="(option,optionIndex) in question.options"
                  :key="optionIndex"
                  :label="`选项${optionIndex + 1}`"
                  :content-flex="false"
                  :merge-props="false">
            <a-form-item label="选项key">
              <a-input v-model="option.key" placeholder="请输入选项key" />
            </a-form-item>
            <a-form-item label="选项值">
              <a-input v-model="option.value" placeholder="请输入选项值" />
            </a-form-item>
            <a-form-item label="选项结果">
              <a-input v-model="option.result" placeholder="请输入选项结果" />
            </a-form-item>
            <a-form-item label="选项得分">
              <a-input-number
                      v-model="option.score"
                      placeholder="请输入选项得分"
              />
            </a-form-item>
            <a-space size="large">
              <a-button size="mini"  @click="addQuestionOptions(question,optionIndex+1)">添加选项</a-button>
              <a-button size="mini"  status="danger" @click="deleteQuestionOptions(question,optionIndex)">删除选项</a-button>
            </a-space>
          </a-form-item>
          <a-divider  dashed />
          <!---->
        </div>
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 120px">
          提交
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
  import {reactive, ref, watchEffect} from 'vue';
  import {userLoginUsingPost} from "@/api/userController";
  import {useLoginUserStore} from "@/store/userStore";
  import message from "@arco-design/web-vue/es/message"
  import {useRouter} from "vue-router";
  import {createAppUsingPost, editAppUsingPost, getAppByIdUsingGet} from "@/api/appController";
  import {APPTYPE_MAP,SCORINGTYPE_MAP} from '@/constant/enum';
  import AiGenerateDrawer from './component/AiGenerateDrawer.vue'
  import {
    createQuestionUsingPost,
    editQuestionUsingPost,
    getQuestionVoByIdUsingGet,
    listQuestionVoByPageUsingPost
  } from "@/api/questionController";

  const loginUserStore = useLoginUserStore();
  const router = useRouter();


  //题目内容结构（理解为题目列表）
  const questionContent = ref<API.QuestionContentDTO[]>([]);

  //添加题目
  const addQuestion = (index:number) =>{
    questionContent.value.splice(index,0,{
      //标题
      title:'',
      //选项
      options:[]
    })
  }

  //删除题目
  const deleteQuestion = (index:number) =>{
    //index：所要删除的元素位置，删除的个数
    questionContent.value.splice(index,1);
  }

  //增加选项
  const addQuestionOptions = (question:API.QuestionContentDTO,index:number) =>{
    question.options?.splice(index,0,{
      key:'',
      value:'',
    })
  };

  //删除选项
  const deleteQuestionOptions = (question:API.QuestionContentDTO,index:number) =>{
    question.options?.splice(index,1);
  }

  //获取前页面跳转过来的参数
  interface Props {
    appId:string
  }
  const props = withDefaults(defineProps<Props>(),{
    appId:() =>{
      return "";
    }
  })

  /**
   * 加载数据
   */
  const oldQuestion = ref<API.QuestionVO>()
  const loadData = async () => {
    if (!props.appId) {
      return;
    }
    const res = await listQuestionVoByPageUsingPost({
      appId: props.appId as any,
      current:1,
      pageSize:1,
      sortField:"createTime",
      sortOrder:"descend"
    });
    if (res.data.code === 0 && res.data.data?.records) {
      oldQuestion.value = res.data.data?.records[0];
      //修改回显
      if(oldQuestion.value){
        questionContent.value = oldQuestion.value.questionContent ?? [];
      }
    } else {
      message.error("获取数据失败，" + res.data.message);
    }
  };

  //提交按钮
   const handleSubmit = async () => {
     if(!props.appId || !questionContent.value){
       return;
     }
    let res : any
    // 如果是修改
    if(oldQuestion.value?.id) {
      res = await editQuestionUsingPost({
        id: oldQuestion.value.id,
        questionContent:questionContent.value
      });
    }
    //创建
    else {
      res = await createQuestionUsingPost({
        appId:props.appId as any,
        questionContent:questionContent.value
      });
    }
    if (res.data.code === 0) {
      message.success("操作成功,即将跳转到应用详情页")
      setTimeout(() =>{
        router.push({
          path: `/app/detail/${props.appId}`,
        })
      },3000)

    } else {
      message.error("操作失败" + res.data.message);
    }
  };

   //将ai生成的题目回显到题目列表中
  const onAiGenerateQuestion = (result:API.QuestionContentDTO[]) => {
    message.success(`AI 生成题目成功，生成 ${result.length} 道题目`);
    questionContent.value = [...questionContent.value,...result]
  }

  //SSE实时将ai生成的题目回显到题目列表中
  const onAiGenerateQuestionSSE = (result:API.QuestionContentDTO) =>{
    questionContent.value = [...questionContent.value,result]
  }

  const onSSEStartGenerate = (event:any) =>{
    message.success("开始生成")
  }

  const onSSEStartClose = (event:any) =>{
    message.success("生成完毕")
  }


  /**
   * 监听 searchParams 变量，改变时触发数据的重新加载
   */
  watchEffect(() =>{
    loadData()
  })

</script>